package com.zjq.authoritysystem.utils;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.Objects;

/**
 * @author Kimiaaaaa
 * @className OssUtil
 * @Description
 * @date 2023-11-08 17:17
 */
@Data
public class OssUtil {
    private String accessKeyId;
    private String accessKey;
    private String bucket;
    private String basePath;
    private String endpoint;


    public OssUtil(String accessKeyId, String accessKey, String bucket, String basePath, String endpoint) {
        this.accessKeyId = accessKeyId;
        this.accessKey = accessKey;
        this.bucket = bucket;
        this.basePath = basePath;
        this.endpoint = endpoint;
    }


    @SneakyThrows
    public String upload(MultipartFile file) {
        String[] strings = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
        String name = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "." + strings[strings.length - 1];
        return upload(file.getInputStream(), name);
    }

    public String upload(InputStream inputStream, String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKey);
        String path = basePath + "/" + fileName;
        PutObjectResult putObjectResult = ossClient.putObject(bucket, path, inputStream);
        return path;
    }
}
